/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.miit.elearning.servlets.pages;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import ru.miit.elearning.hibernate.dao.AnnouncementDAO;
import ru.miit.elearning.hibernate.dao.CourseDAO;
import ru.miit.elearning.hibernate.dao.HibernateUtil;
import ru.miit.elearning.hibernate.dto.Announcement;
import ru.miit.elearning.hibernate.dto.CurriculumLevel;

/**
 *
 * @author Cyclone
 */
public class AnnouncementsServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        Session session = null;
        try {

            int page = 1;
            int rowCount = 10; // PAGING DISABLED
            //int rowCount = Integer.MAX_VALUE;

            try {
                String pageString = request.getParameter("page");
                if (pageString != null) {
                    page = Integer.parseInt(pageString);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                String rowNumString = request.getParameter("view");
                if (rowNumString != null) {
                    rowCount = Integer.parseInt(rowNumString);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();

            AnnouncementDAO announcementDAO = new AnnouncementDAO(session);

            int currentUserId = announcementDAO.findUserIdByLogin(request.getRemoteUser());

/*
            long totalRows = 0;
            if (request.isUserInRole("admin")) {
                totalRows = announcementDAO.countAllAnnouncements();
            } else {
                totalRows = announcementDAO.countAnnouncementsByUser(currentUserId);
            }

            int totalPages = new Double(Math.ceil((double) totalRows / rowCount)).intValue();

            // 1 <= page <= totalPages
            page = Math.min(Math.max(1, page), totalPages);
*/

            List<Announcement> announcementList = null;
            if(request.isUserInRole("admin")) {
                announcementList = announcementDAO.findAnnouncementsByPage((page - 1) * rowCount, rowCount);
            } else {
                announcementList = announcementDAO.findAnnouncementsByPageByUser((page - 1) * rowCount, rowCount, currentUserId);
            }



            List<CurriculumLevel> directionList = null;
            CourseDAO courseDAO = new CourseDAO(session);
            if (request.isUserInRole("admin")) {
                directionList = courseDAO.findAllDirections();

                for (CurriculumLevel direction : directionList) {
                    request.setAttribute("courseList_" + direction.getId(), new ArrayList(direction.getCurriculumLevels()));
                }
            } else {
                if (request.isUserInRole("tutor")) {

                    directionList = courseDAO.findDirectionsByTutor(currentUserId);

                    for (CurriculumLevel direction : directionList) {
                        request.setAttribute("courseList_" + direction.getId(), new ArrayList(courseDAO.findCoursesByTutorByDirection(currentUserId, direction.getId())));
                    }
                }
            }
            courseDAO = null;



            request.setAttribute("directionList", directionList);
            request.setAttribute("announcementList", announcementList);

            getServletContext().getRequestDispatcher("/announcements.jsp").forward(request, response);
            if (session != null && session.isOpen()) {
                session.getTransaction().commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
            getServletContext().setAttribute("message", "Произошла ошибка запроса списка объявлений");
            getServletContext().getRequestDispatcher("/announcements.jsp").forward(request, response);
            if (session != null && session.isOpen()) {
                session.getTransaction().rollback();
            }

        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
